package com.zhuiyun.project.api.appLogin.service.impl;

import com.zhuiyun.project.api.appLogin.service.AppLoginService;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.security.jwt.JWTUtils;
import com.zhuiyun.project.utils.ObjectUtils;
import com.zhuiyun.project.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @ClassName AppLoginServiceImpl
 * @Description TODO
 * @Author ys
 * @Date 2023/11/14 8:51
 **/
@Service
@Slf4j
public class AppLoginServiceImpl implements AppLoginService {
    /**
     * @param phone
     * @Description 腾讯云发送手机短信
     * @Author HH
     * @Date 2023/4/12 9:43
     * @Return com.zhuiYun.project.common.response.CommonResult
     */
    @Override
    public CommonResult sendPhoneCode(String phone) {
        // 生成验证码
        String newCode = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            newCode += random.nextInt(10);
        }
//        boolean send = send(phone, newCode);
        log.info(newCode);

            // 查询redis有没有验证码
            String code = (String) RedisUtil.get("CACHE_PHONE_CODE" + phone);
            // 有的话先删除
            if (ObjectUtils.isNotEmpty(code)) {
                RedisUtil.del("CACHE_PHONE_CODE" + phone);
            }
            RedisUtil.set("CACHE_PHONE_CODE" + phone, newCode, 600);
            return CommonResult.ok(newCode);
        }
    /**
     * @param phone
     * @param code
     * @Description 判断手机短信验证码是否正确
     * @Author HH
     * @Date 2023/4/12 13:56
     * @Return com.zhuiYun.project.common.response.CommonResult
     */
    @Override
    public CommonResult verificationCode(String phone, String code) {
        String redisCode = (String) RedisUtil.get("CACHE_PHONE_CODE" + phone);
        if (ObjectUtils.isNotEmpty(redisCode)) {
            if (redisCode.equals(code)) {
                RedisUtil.set("CACHE_token_CODE" , phone, 86400);
                return CommonResult.ok();
            } else {
                return CommonResult.error(EmErrorCode.CODE_IS_ERROR);
            }
        } else {
            return CommonResult.error(EmErrorCode.CODE_IS_ERROR);
        }
    }

    @Override
    public CommonResult getToken() {
        String Token= (String) RedisUtil.get("CACHE_token_CODE");
        if(ObjectUtils.isNotEmpty(Token)){
            return CommonResult.ok(1);
        }else{
            return CommonResult.ok(EmErrorCode.TOKEN_EXPIRE);
        }
    }
}
